package Day2;

/**
 * @author ：Yan Guang
 * @date ：Created in 2020/4/27 18:32
 * @description：生产者消费者问题
 * 1多线程：生产者线程，消费者线程
 * 2需要共享数据，店员或者产品
 * 3需要解决线程安全问题，同步机制(同步就相当于是互斥)
 * 4涉及到通信
 */
class Clerk{
    private int productCount=0;
    public synchronized void produceProduct() {//生产
        if (productCount<20){
            productCount++;
            System.out.println(Thread.currentThread().getName()+"开始生产第"+productCount+"个产品");
            notify();
        }else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void consumeProduct() {//消费
         if (productCount>0){
             System.out.println(Thread.currentThread().getName()+"开始消费"+productCount+"个产品");
             productCount--;
             notify();
         }else {
             try {
                 wait();
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
         }
    }
}
class Producer extends Thread{
    private Clerk clerk;

    public Producer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+":开始生产产品....");
        while (true){
            clerk.produceProduct();
        }
    }
}
class Consumer extends Thread{
    private Clerk clerk;

    public Consumer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+":开始生产产品....");
        while (true){
            clerk.consumeProduct();
        }
    }
}
public class ProuductTest {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        Producer p1 = new Producer(clerk);
        p1.setName("生产者一");

        Consumer c1=new Consumer(clerk);
        c1.setName("消费者一");

        p1.start();
        c1.start();
    }
}
